package csu.web.jpetstore.web.servlet;

import csu.web.jpetstore.domain.Cart;
import csu.web.jpetstore.domain.CartItem;
import csu.web.jpetstore.domain.Item;
import csu.web.jpetstore.persistence.impl.LoggerDAOImpl;
import csu.web.jpetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

import static csu.web.jpetstore.persistence.impl.LoggerDAOImpl.loginLogger;

public class AddItemToCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String workingItemId = req.getParameter("workingItemId");
        LoggerDAOImpl loggerDAO=new LoggerDAOImpl();
        loginLogger.setStarttime();
        loginLogger.setAction(loginLogger.getUsername()+"下单");
        try {
            loggerDAO.logger(loginLogger);
        } catch (SQLException e) {
            e.printStackTrace();
        }


        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");

        String random_now = req.getParameter("random");
        String random_last;
        if (session.getAttribute("random")==null){
            random_last=random_now;
        }else{
            random_last= session.getAttribute("random").toString();
        }

        if(cart == null){
            cart = new Cart();
        }

        if (cart.containsItemId(workingItemId)&!random_now.equals(random_last)) {//获取添加到cart的itemId
            cart.incrementQuantityByItemId(workingItemId);
        } else {
            CatalogService catalogService = new CatalogService();
            boolean isInStock = catalogService.isItemInStock(workingItemId);
            Item item = catalogService.getItem(workingItemId);
            CartItem cartItem=cart.addItemAndReturnCartItem(item, isInStock);//对cart的itemMap和itemList存值
            if (session.getAttribute("random")==null){
                cartItem.incrementQuantity();
            }else if (!random_now.equals(random_last)){
                cartItem.incrementQuantity();
            }
        }

        session.setAttribute("random",random_now);
        session.setAttribute("cart", cart);
        req.getRequestDispatcher(CART_FORM).forward(req, resp);
    }
}
